<?php

namespace App\Http\Requests\Admin\User\Menu;

use App\Models\Menu;
use App\Models\Permission;
use App\Models\Role;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\Request;
use Illuminate\Validation\Rule;

class UpdateRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        $menu = Request::route('menu');
        $id = $menu->id;
        $gid = $menu->menu_group_id;
        return [
            'is_auth' => ['required', 'boolean', 'bail'],
            'label' => ['required', 'max:20', 'bail'],
            'route' => ['required',
                Rule::unique('menus')->where(function($query)use($gid){
                    return $query->where([
                        'menu_group_id'=>$gid
                    ]);
                })->ignore($id)
                ,'max:20', 'bail'],
            'status' => ['required', 'boolean', 'bail'],
            'sort' => ['required', 'numeric', 'bail', 'max:1000'],
            'permissions' => [function ($attribute, $value, $fail) {
                $count = count($value);
                $database_count = Permission::whereIn('id', $value)->count();
                if ($count != $database_count) {
                    $fail(':attribute数据错误');
                }
            },
                'bail'],
            'roles'=>[function($attribute,$value,$fail){
                $count = count($value);
                $database_count = Role::whereIn('id', $value)->count();
                if ($count != $database_count) {
                    $fail(':attribute数据错误');
                }
            }]
        ];
    }

    public function attributes()
    {
        return Menu::$attributesMap;
    }
}
